﻿<style>
    .shape {
        width: 100px;
        height: 100px;
        background-color: #FF0000;
    }
</style>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/knockout-3.1.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
<script src="~/signalr/hubs"></script>

<div class="shape" style="width:500px;height:500px;" data-bind="myBind:{top:Top,left:Left,move:Move}"></div>
<script>
    var hub = $.connection.moveHub;
    var moveModel = ko.mapping.fromJS({
        Top: 0,
        Left: 0,
        Move: function () {
            hub.server.updateModel(ko.toJS(moveModel));
        }
    });

    ko.bindingHandlers["myBind"] = {
        'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var valA = valueAccessor();
            var el = $(element);
            el.draggable({
                drag: function () {
                    var offset = el.offset();
                    valA.left(offset.left);
                    valA.top(offset.top);
                    valA.move();
                }
            });
        },
        'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var valA = valueAccessor();
            var el = $(element);
            el.offset({ top: valA.top(), left: valA.left() });

        }

    };
    hub.client.sendMove = function (model) {
        moveModel.Top(model.Top);
        moveModel.Left(model.Left);

    };
    $.connection.hub.start();
    ko.applyBindings(moveModel);

</script>